//
//  SSPlayingViewController.swift
//  QQ音乐
//
//  Created by 叶竞泽 on 2017/5/17.
//  Copyright © 2017年 叶竞泽. All rights reserved.
//

import UIKit
import AVFoundation

protocol SSPlayingViewControllerDelegate: NSObjectProtocol {
    func resumeAnimation(view: UIView)
    func pauseAnimation(view: UIView)
}

class SSPlayingViewController: UIViewController {
    
    // MARK: - 属性
    
    /// 进度条
    @IBOutlet weak var slider: UISlider!
    /// 封面
    @IBOutlet weak var coverImageView: UIImageView!
    /// 歌手名字
    @IBOutlet weak var author: UILabel!
    /// 音乐名字
    @IBOutlet weak var musicName: UILabel!
    /// 歌曲当前时间
    @IBOutlet weak var startTimeLabel: UILabel!
    /// 歌曲剩余时间
    @IBOutlet weak var endTimeLabel: UILabel!
    /// 开始按钮
    @IBOutlet weak var startButton: UIButton!
    /// 上一首按钮
    @IBOutlet weak var preSongButton: UIButton!
    /// 下一首按钮
    @IBOutlet weak var nextSongButton: UIButton!
    /// 歌词视图
    @IBOutlet weak var lrcsScrollView: UIScrollView!
    /// 音乐数据列表
    lazy var musicDataList: [SSMusic]? = SSMusicList.shared.musicList
    /// 模糊视图
    lazy var effectView: UIVisualEffectView = {
        let blur = UIBlurEffect(style: .dark)
        let effectView = UIVisualEffectView(effect: blur)
        effectView.frame = UIScreen.main.bounds
        return effectView
    }()
    /// 背景图片名字
    fileprivate var backgroundImageName: String? {
        didSet {
            if let name = backgroundImageName {
                guard let image = UIImage(named: name) else { return }
                view.layer.contents = image.cgImage
            }
        }
    }
    /// 存储所有播放器,key是歌名
    fileprivate lazy var musicPlayerDict: [String: AVAudioPlayer]? = SSMusicList.shared.players
    /// 当前正在播放的播放器
    fileprivate var currentPlayer: AVAudioPlayer? {
        didSet {
            let appDelegate = AppDelegate()
        }
    }
    /// 是否在播放
    fileprivate var isPlaying = false
    /// 计时器
    fileprivate var timer: Timer?
    /// 当前歌曲
    fileprivate var currentMusic: SSMusic? {
        didSet {
            // 设置歌名和作者
            musicName.text = musicDataList?[0].name
            author.text = musicDataList?[0].singer
            // 设置封面
            coverImageView.image = UIImage(named: musicDataList?[0].icon ?? "")
        }
    }
    /// 当前在进行的动画
    fileprivate var currentAnimation: CABasicAnimation?
    /// 是否在进行动画
    fileprivate var isAnimating = false
    
    // MARK: - 方法
    
    /// 根据歌曲信息设置进度条内容,让进度条开始走动
    fileprivate func setupProgressAndTimeLabel() {
        slider.minimumValue = 0
        slider.maximumValue = Float(self.currentPlayer?.duration ?? 0)
        if timer == nil {
            timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] (timer) in
                self?.slider.setValue(Float(self?.currentPlayer?.currentTime ?? 0), animated: true)
                self?.startTimeLabel.text = self?.timeStr(withTimeInterval: (self?.currentPlayer?.currentTime ?? 0))
                self?.endTimeLabel.text = self?.timeStr(withTimeInterval: (self?.currentPlayer?.duration ?? 0))
            }
        } else {
            slider.setValue(Float(currentPlayer?.currentTime ?? 0), animated: true)
            startTimeLabel.text = timeStr(withTimeInterval: (currentPlayer?.currentTime ?? 0))
            endTimeLabel.text = timeStr(withTimeInterval: (currentPlayer?.duration ?? 0))
        }
    }
    /// 开始动画
    func startAnimation(view: UIView) {
        currentAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        currentAnimation?.toValue = 2 * Float.pi
        currentAnimation?.repeatCount = MAXFLOAT
        currentAnimation?.duration = 10
        currentAnimation?.isRemovedOnCompletion = false
        currentAnimation?.fillMode = kCAFillModeForwards
        view.layer.add(currentAnimation!, forKey: "transform.rotation.z")
        isAnimating = true
    }
    /// 暂停动画
    func pauseAnimation(view: UIView) {
        let pauseTime = view.layer.convertTime(CACurrentMediaTime(), from: nil)
        view.layer.speed = 0
        view.layer.timeOffset = pauseTime
        isAnimating = false
    }
    /// 恢复动画
    func resumeAnimation(view: UIView) {
        let pauseTime = view.layer.timeOffset
        view.layer.speed = 1
        view.layer.timeOffset = 0
        view.layer.beginTime = 0
        let timeSincePause = view.layer.convertTime(CACurrentMediaTime(), from: nil) - pauseTime
        view.layer.beginTime = timeSincePause
        isAnimating = true
    }
    /// 旋转视图
    fileprivate func rotate(view: UIImageView) {
        if currentAnimation == nil {
            startAnimation(view: view)
        } else {
            if isAnimating {
                pauseAnimation(view: view)
            } else {
                resumeAnimation(view: view)
            }
        }
    }
    
    /// 开始或暂停播放
    @IBAction func play(_ sender: UIButton) {
        if isPlaying {
            currentPlayer?.pause()
            isPlaying = false
        } else {
            if currentPlayer != nil {
                currentPlayer?.play()
                isPlaying = true
            } else {
                if musicPlayerDict?[musicDataList?[0].name ?? ""]?.prepareToPlay() == true {
                    musicPlayerDict?[musicDataList?[0].name ?? ""]?.play()
                    isPlaying = true
                    currentPlayer = musicPlayerDict?[musicDataList?[0].name ?? ""]
                }
            }
        }
        // 设置播放按钮暂停图片
        setupStartButtonImage()
        // 设置进度条和时间
        setupProgressAndTimeLabel()
        // 旋转cover视图
        rotate(view: coverImageView)
        // 设置当前正在播放的歌曲
        SSMusicList.shared.currentPlayingSong = currentMusic
    }
    
    /// 开始下一首
    @IBAction func next(_ sender: UIButton) {
        
    }
    
    /// 开始上一首
    @IBAction func previous(_ sender: UIButton) {
        
    }
    
    /// 设置开始按钮的图片
    fileprivate func setupStartButtonImage() {
        if isPlaying {
            startButton.setImage(UIImage(named: "player_btn_pause_normal"), for: .normal)
            startButton.setImage(UIImage(named: "player_btn_pause_highlight"), for: .highlighted)
        } else {
            startButton.setImage(UIImage(named: "player_btn_play_normal"), for: .normal)
            startButton.setImage(UIImage(named: "player_btn_play_highlight"), for: .highlighted)
        }
    }
    
    /// 根据秒数返回分钟+秒
    fileprivate func timeStr(withTimeInterval time: TimeInterval) -> String {
        let min = Int(time) / 60
        let sec = Int(time) % 60
        var minStr = "\(min):"
        var secStr = "\(sec)"
        if min < 10 {
            minStr = "0\(min):"
        }
        if sec < 10 {
            secStr = "0\(sec)"
        }
        return minStr + secStr
    }
    
    /// 监听slider的值改变
    @objc fileprivate func sliderChanged(sender: UISlider) {
        guard let player = currentPlayer else { return }
        player.currentTime = TimeInterval(exactly: sender.value)!
        setupProgressAndTimeLabel()
    }
    /// 监听slider点击
    @objc fileprivate func sliderClick(sender: UITapGestureRecognizer) {
        let point = sender.location(in: sender.view)
        let offsetX = point.x
        let ratio = offsetX / (sender.view?.bounds.width ?? 0)
        currentPlayer?.currentTime = (currentPlayer?.duration)! * (TimeInterval(exactly: Float(ratio))!)
    }
    
    // MARK: - 生命周期
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupSlider()
        currentMusic = musicDataList?[0]
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        setupUI()
    }
    
    deinit {
        timer?.invalidate()
    }
}

// MARK: - 设置界面
extension SSPlayingViewController {
    fileprivate func setupUI() {
        // 设置cover视图为圆角
        coverImageView.sizeToFit()
        coverImageView.layer.cornerRadius = (coverImageView.image?.size.width)! / 2
        coverImageView.layer.masksToBounds = true
        // 设置毛玻璃效果
        backgroundImageName = "bb@2x.jpg"
        view.insertSubview(effectView, at: 0)
    }
    fileprivate func setupSlider() {
        slider.addTarget(self, action: #selector(sliderChanged(sender:)), for: .valueChanged)
        slider.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(sliderClick(sender:))))
    }
}
